package com.lanlian.cayman.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.lanlian.commonlib.base.BaseActivity;
import com.lanlian.commonlib.bean.db.DBMarketS;
import com.lanlian.commonlib.data.ContractBean;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.util.LogUtils;
import com.lanlian.commonlib.util.OnEventID;
import com.lanlian.commonlib.util.OnEventUtils;
import com.lanlian.cayman.HqMsg;
import com.lanlian.cayman.R;
import com.lanlian.cayman.adapter.NewMarketAdapter;
import com.lanlian.cayman.bean.EventZixuanData;
import com.lanlian.cayman.bean.MyContractBean;
import com.lanlian.cayman.fragment.MarketFragment;
import com.lanlian.cayman.proto.ProtoManager;
import com.lanlian.cayman.socket.MySocketManager;
import com.lanlian.cayman.socket.SocketCallImpl;
import com.oms.rpc.protobuf.OMSTradeReq;
import com.oms.rpc.protobuf.OMSTradeRsp;
import com.oms.rpc.protobuf.TickHqResp;
import com.oms.rpc.protobuf.YsHqInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/10/25 18:21
 *     desc   : 单独自选页面
 *     version: 1.0
 * </pre>
 */
public class ZixuanActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout mLayEmpty;
    private LinearLayout mLayContent;
    private ListView mRecycleView;

    private NewMarketAdapter adapter;

    private ArrayList<MyContractBean> myContractBeans = new ArrayList<>();
    private boolean mIsScrolling;
    private boolean mIsResume;
    private TickHqResp mTickHqResp;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zixuan, true);
        initView();
        initAdapter();
        setListeners();
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("自选");
        setRightStr("行情");
        mLayEmpty = findViewById(R.id.lay_empty);
        mLayContent = findViewById(R.id.lay_content);
        mRecycleView = findViewById(R.id.recycle_view);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mTvAction.setOnClickListener(this);
    }

    private void initAdapter() {
        myContractBeans = selectMarketItem(MarketFragment.getRespMarket().getContractList());
        getTickHq();
        setEmptyView();
        adapter = new NewMarketAdapter(this, myContractBeans, null);
        mRecycleView.setAdapter(adapter);
        mRecycleView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OnEventUtils.onEvent(ZixuanActivity.this, OnEventID.CONTRACT,
                        myContractBeans.get(position).name + myContractBeans.get(position).id);
                Intent intent = new Intent();
                intent.setClass(ZixuanActivity.this, KLineActivity.class);
                intent.putExtra("name", myContractBeans.get(position).name);
                intent.putExtra("id", myContractBeans.get(position).id);
                startActivity(intent);
            }
        });
        mRecycleView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case SCROLL_STATE_IDLE:
                        //滑动停止时调用
                        mIsScrolling = false;
                        break;
                    case SCROLL_STATE_TOUCH_SCROLL:
                        //正在滚动时调用
                        mIsScrolling = true;
                        break;
                    case SCROLL_STATE_FLING:
                        //手指快速滑动时,在离开ListView由于惯性滑动
                        mIsScrolling = true;
                        break;
                    default:
                        mIsScrolling = false;
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    private void getTickHq() {
        ProtoManager pm = new ProtoManager();
        OMSTradeReq.Builder oms = pm.getRequst(6);
        OMSTradeReq om = oms.build();
        SocketCallImpl socketCall = new SocketCallImpl(this) {
            @Override
            public void error(Exception e) {
            }

            @Override
            public void message(byte[] data) {
                try {
                    OMSTradeRsp oms = OMSTradeRsp.parseFrom(data);
                    mTickHqResp = oms.getTickhqResp();
                    setData();
                } catch (Exception e) {
                    LogUtils.e("MarketFragment", e.getMessage());
                }
            }
        };
        MySocketManager ms = new MySocketManager();
        ms.sendData(om.toByteArray(), socketCall);
    }

    private void setData() {
        if (mTickHqResp != null) {
            for (YsHqInfo ysHqInfo : mTickHqResp.getTickhqinfoList()) {
                updateAdapter(exchangeData(ysHqInfo));
            }
        }
    }

    private HqMsg.YsHqInfo exchangeData(YsHqInfo ysHqInfo) {
        HqMsg.YsHqInfo.Builder builder = HqMsg.YsHqInfo.newBuilder();
        builder.setCommodityNo(ysHqInfo.getCommodityNo());
        builder.setContractNo1(ysHqInfo.getContractNo1());
        builder.setQOpeningPrice(ysHqInfo.getQOpeningPrice());
        builder.setQLastPrice(ysHqInfo.getQLastPrice());
        builder.setQChangeRate(ysHqInfo.getQChangeRate());
        builder.setQChangeValue(ysHqInfo.getQChangeValue());
        return builder.build();
    }

    private ArrayList<MyContractBean> selectMarketItem(ArrayList<ContractBean> list) {
        ArrayList<MyContractBean> select = new ArrayList<>();
        for (ContractBean bean : list) {
            if (isZiXuan(bean.contractNo)) {
                MyContractBean contractBean = new MyContractBean();
                contractBean.id = bean.contractNo;
                contractBean.name = bean.contractName;
                select.add(contractBean);
            }
        }
        return select;
    }

    public void updateAdapter(HqMsg.YsHqInfo ysHqInfo) {
        for (MyContractBean myContractBean : myContractBeans) {
            if (myContractBean.id.equals(ysHqInfo.getCommodityNo() + ysHqInfo.getContractNo1())) {
                myContractBean.open = ysHqInfo.getQOpeningPrice() + "";
                myContractBean.last = ysHqInfo.getQLastPrice() + "";
                myContractBean.chg = ysHqInfo.getQChangeRate() + "";
                myContractBean.change = ysHqInfo.getQChangeValue() + "";
                adapter.notifyDataSetChanged(mRecycleView, myContractBeans.indexOf(myContractBean));
                break;
            }
        }
    }

    public void updateZixuan(MyContractBean myContractBean, boolean isAdd) {
        if (isAdd) {
            myContractBeans.add(myContractBean);
            setEmptyView();
            adapter.notifyDataSetChanged();
        } else {
            for (MyContractBean contractBean : myContractBeans) {
                if (contractBean.id.equals(myContractBean.id)) {
                    int position = myContractBeans.indexOf(contractBean);
                    myContractBeans.remove(position);
                    setEmptyView();
                    adapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    }

    private boolean isZiXuan(String id) {
        List<DBMarketS> list = mDBManager.getMarketS();
        if (list != null) {
            for (DBMarketS dbMarketS : list) {
                if (id.equals(dbMarketS.getId())) {
                    return true;
                }
            }
        }
        return false;
    }

    private void setMarket(HqMsg.YsHqInfo ysHqInfo) {
        if (ysHqInfo == null) {
            return;
        }
        if (mIsResume && !mIsScrolling) {
            updateAdapter(ysHqInfo);
        }
    }

    private void setEmptyView() {
        if (myContractBeans.size() == 0) {
            mLayContent.setVisibility(View.GONE);
            mLayEmpty.setVisibility(View.VISIBLE);
        } else {
            mLayContent.setVisibility(View.VISIBLE);
            mLayEmpty.setVisibility(View.GONE);
        }
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        switch (event.getCode()) {
            case EventCode.EVENT_ZIXUAN_REFRESH:
                EventZixuanData eventZixuanData = (EventZixuanData) event.getData();
                if (eventZixuanData.isAdd()) {
                    OnEventUtils.onEvent(this, OnEventID.CONTRACT_ADD);
                } else {
                    OnEventUtils.onEvent(this, OnEventID.CONTRACT_DELETE);
                }
                updateZixuan(eventZixuanData.getContractBean(), eventZixuanData.isAdd());
                break;
            case EventCode.EVENT_MARKET:
                HqMsg.YsHqInfo ysHqInfo = (HqMsg.YsHqInfo) event.getData();
                setMarket(ysHqInfo);
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_action) {
            startActivity(new Intent(this, MainActivity.class)
                    .putExtra("item", 0));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mIsResume = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsResume = true;
    }

}
